<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/8
 * Time: 9:04 AM
 */

namespace app\api\controller;


use app\api\job\SendNotify;
use app\common\controller\ActionLogs;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\TemplateMsg;
use app\common\model\ActionLog;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\Tklog;

class Notify
{
    public function starpos()
    {
        $postData = file_get_contents('php://input');
        if ($postData) {

            $encode = mb_detect_encoding($postData, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
            $postData = iconv($encode, 'UTF-8', $postData);
            $postData = json_decode($postData, true);
            if ($postData['TxnCode'] == "L020") {

                if ($postData['TxnStatus'] == 1) {
                    $Paylog = new Paylog();
                    $map['orderid'] = $postData['ChannelId'];
                    $payinfo = $Paylog->where($map)->find();
                    $data['pay_statu'] = 1;
                    $data['orderno'] = $postData['TxnLogId'];
                    $pay_time = strtotime($postData['TxnDate'] . $postData['TxnTime']);
                    $data['pay_time'] = date('Y-m-d H:i:s', $pay_time);
                    $data['payinfo'] = json_encode($postData);
                    $Paylog->save($data, $map);
                    if ($payinfo['tzzt'] == 0) {
                        $TemplateMsg = new TemplateMsg();
                        $TemplateMsg->send_tpl('pay', array('merchantid' => $payinfo['mid'], 'orderid' => $payinfo['orderid']));
                        $FeiePrint = new FeiePrint();
                        $FeiePrint->sendprint($payinfo['orderid']);
//                        $Deviceobj = new Deviceobj();
//                        $s=$Deviceobj->ylb_sendvoice($payinfo['orderid']);
                    }
                }
            } elseif ($postData['TxnCode'] == "L030") {
                $Paylog = new Paylog();
                $map['orderid'] = $postData['ChannelId'];
                $orderinfo = $Paylog->where($map)->find();

                $sedata['tk_price'] = $orderinfo['tk_price'] + $postData['TxnAmt'];
                $Paylog->save($sedata, $map);
                $params['orderid'] = $orderinfo['orderid'];
                $params['mid'] = $orderinfo['mid'];
                $params['addtime'] = time();
                $params['action_user'] = "";
                $params['tk_fs'] = "星POS";
                $params['pid'] = $orderinfo['id'];
                $params['refund_fee'] = $postData['TxnAmt'];
                $params['tk_orderid'] = $postData['logNo'];
                if ($postData['TxnStatus'] == 1) {
                    $params['tk_status'] = 1;
                } else {
                    $params['tk_status'] = 3;
                }
                $params['tk_info'] = json_encode($params, JSON_UNESCAPED_UNICODE);
                $Tklog = new Tklog();
                $Tklog->save($params);

            }
        }

        echo "success";
    }

    public function wxofficialnotify()
    {
        $ActionLogs = new ActionLogs();
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)) {
            //微信支付事件接收
            $ActionLogs->writelog("payos", "wxauth", "event/wxpaynotify", "接收推送信息:", $postStr);
            libxml_disable_entity_loader(true);
            $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);


            if (isset($msg['return_code'])) {

                $pay_zt = $msg['return_code'];
                if ($pay_zt == "SUCCESS") {
                    $Paylog = new Paylog();
                    $data['pay_statu'] = 1;
                    $payinfo = $Paylog->where(['orderid' => $msg['out_trade_no']])->field('tzzt,mid')->find();

                    if ($payinfo['tzzt'] == '0') {
                        $notify_param['out_trade_no'] = $msg['out_trade_no'];
                        $notify_param['merchantid'] = $payinfo['mid'];
                        $OfficialPay = new OfficialPay();
                        $OfficialPay->wxcheckpay($notify_param);
                        $this->sendnotify($notify_param);
                    } elseif ($payinfo['tzzt'] == 1) {
                        $su = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        echo $su;
                    }
                }

            }
        }
    }
    public function aliofficialnotify(){

        $msg = array();
        $request = request();
        if ($request->isPost()) {
            $msg = $request->post();
            $pay_zt = $msg['trade_status'];
            if ($pay_zt == "TRADE_SUCCESS") {

                $Paylog = new Paylog();
                $id = $Paylog->where(array('orderid' => $msg['out_trade_no']))->find();
                if ($id['tzzt'] == 0) {
                    if ($id['tzzt'] == '0') {
                        $notify_param['out_trade_no'] = $msg['out_trade_no'];
                        $notify_param['merchantid'] = $id['mid'];
                        $OfficialPay = new OfficialPay();
                        $OfficialPay->alicheckpay($notify_param);
                        $this->sendnotify($notify_param);
                    } elseif ($id['tzzt'] == 1) {
                        $su = 'success';
                        echo $su;
                    }

                }

            }

        }

    }


    public function wxofficialappnotify(){
        $ActionLogs = new ActionLogs();
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)) {
            //微信支付事件接收
            $ActionLogs->writelog("payos", "wxauth", "event/wxpaynotify", "接收推送信息:", $postStr);
            libxml_disable_entity_loader(true);
            $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);


            if (isset($msg['return_code'])) {
                if ($msg['return_code'] == "SUCCESS") {
                    $Paylog = new Paylog();
                    $map['orderid'] = $msg['out_trade_no'];
                    $payinfo = $Paylog->where($map)->find();
                    if ($payinfo) {
                        if ($payinfo['tzzt'] == '0') {
                            $notify_param['out_trade_no'] = $msg['out_trade_no'];
                            $notify_param['merchantid'] = $payinfo['mid'];
                            $WxAppCreateOrder = new WxAppCreateOrder();
                            $WxAppCreateOrder->wxorderquery($notify_param);
                            $this->sendnotify($notify_param);
                        } elseif ($payinfo['tzzt'] == 1) {
                            $res = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                            echo $res;
                        }
                    }
                }
            }
        }

    }


   public function test(){
//    $url="http://property.wunengkeji.com/notify.php/syncnotify";
    $str='{"merchantid":"501","posTermId":"","pospSeqId":"982117","agentId":"310000015000064160","openId":"o8jhot5YB76jWhofDS_heyM8b8ps","merFee":"0.00","partyOrderId":"18120129T4469178","shopName":" ","ordId":"20181201E10007161653","payType":"null ","cashOrdId":"20181201E10007161653","subOpenId":"oWBok0QJtZiywLyPB4EEoggtZjNA","transDate":"20181201","checkValue":"TUlJSHdnWUpLb1pJaHZjTkFRY0NvSUlIc3pDQ0I2OENBUUV4RHpBTkJnbGdoa2dCWlFNRUFnRUZBRENDQVNrR0NTcUdTSWIzRFFFSEFhQ0NBUm9FZ2dFV01qQXhPREV5TUR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hXWGNpUjd2YlEwL0VTVWhzSlhZSXg1b3RiczBzdWF5c2xYY0xGeXVrTmNvWHFxM2NDYkViNjBkdnhKMlFQR3RVWkZ0ZUJRRDMwUnlaUjJOOEg2QWVtWTQwODJ6S2ZhUVhBYmJrMjVvOHp0S2RGQ2s3SWNQZElrZnZYeDZjUXRYU0VzSENXZ0lUSnAvK3BmV0JjRVJUejc5WjZ3SlhGREMvcXlmeUNFaWc9PQ==","debitFlag":"","transTime":"171530","openBuyerId":"oWBok0QJtZiywLyPB4EEoggtZjNA","merchName":"安阳布朗斯通网络科技有限公司","merPriv":"{\"merNoticeUrl\":\"https:\/\/api.wunengkeji.com\/notify.php\/huifunotify\"}","bankType":"","payTypeDetail":"null ","transStat":"S","agentName":"河南悟能网络科技有限公司","merOrdId":"","merchId":"310000016000142906","outTransId":"4200000223201812010525856054","transType":"1000","refNum":"0","ordAmt":"0.01","respMsg":"","respCode":"000000","termOrdId":"H912f2018120117152982117"}';
       $SendNotify=new SendNotify();
       $ss=$SendNotify->task_biz_notify($str);
//       $ss= $this->http_post($url, $str, $post_file = false);
    var_dump($ss);
   }
    public function huifunotify()
    {

        $postStr = request()->param();
        $ActionLogs=new ActionLogs();
        $ActionLogs->writelog("osapi", "notify", "event/sendnotify", "接收推送信息:", $postStr);

        if ($postStr) {
            if ($postStr['respCode'] == "000000") {

                $Paylog = new Paylog();
                $payinfo = $Paylog->where(['orderid' => $postStr['termOrdId']])->field('tzzt,mid')->find();

                if ($payinfo['tzzt'] == '0') {

                    $notify_param['out_trade_no'] =$postStr['termOrdId'];
                    $notify_param['merchantid'] = $payinfo['mid'];
                    $OfficialPay = new Huifupay();
                    $OfficialPay->checkpay($notify_param);
                    $this->sendnotify($notify_param);
                } elseif ($payinfo['tzzt'] == 1) {
                    return "NO_RECV_ORD_ID_" . $postStr['ordId'];
                }

            }
        }
    }

    private function sendnotify($param)
    {
        $Paylog = new Paylog();
        $payinfo = $Paylog->where('orderid', $param['out_trade_no'])->find();
        if ($payinfo['pay_statu'] == 1) {
            if (!empty($payinfo['cashier'])) {
                $device_id = $payinfo['cashier'];

            } elseif (!empty($payinfo['d_cashier'])) {
                $device_id = $payinfo['d_cashier'];

            } else {
                $device_id = "";
            }
            $arrc['return_code'] = "SUCCESS";
            $arrc['result_code'] = "SUCCESS";
            $arrc['return_msg'] = "支付成功";
            $arrc['result_msg'] = "支付成功";
            $arrc['notify_category'] = "pay";
            $arrc['out_trade_no'] = $payinfo['orderid'];
            $arrc['trade_no'] = $payinfo['trade_no'];
            $arrc['order_no'] = $payinfo['orderno'];
            $arrc['total_fee'] = $payinfo['price'];//实付金额
            $arrc['channel'] = $payinfo['pay_fs'];//实付金额
            $arrc['merchantname'] = getmerchant($payinfo['mid']);//商户名称
            $arrc['ought_fee'] = $payinfo['yf_price'];//应付金额
            $arrc['gel_fee'] = $payinfo['zk_price'];//折扣金额
            $arrc['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
            $arrc['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
            $arrc['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
            $arrc['service_charge'] = $payinfo['service_charge'];        //手续费
            $arrc['end_time'] = !empty($payinfo['pay_time']) ? $payinfo['pay_time'] : "";//支付时间
            $arrc['gel_info'] = getdeduzkinfo($payinfo['hx_card'], $payinfo['gel_card_zk']);        //抵扣明细
            $arrc['openid'] = $payinfo['openid'];       //抵扣明细
            $arrc['sub_openid'] = $payinfo['sub_openid'];       //抵扣明细
            $arrc['attach'] = $payinfo['attach'];       //抵扣明细

            $arrc['device_id'] = $device_id;     //收银员
//        $arrc['is_vip'] = "";        //是否会员
//        $arrc['is_fans'] = "";        //是否粉丝
//        $arrc['card_name'] = "";        //会员姓名
//        $arrc['card_num'] = "";        //会员卡号
            $Merchant = new Merchant();
            $notify_url = $Merchant->where('id', $param['merchantid'])->value('notify_url');
            if (!empty($notify_url)) {
                $ActionLogs=new ActionLogs();
                $r=$this->http_post($notify_url, json_encode($arrc, JSON_UNESCAPED_UNICODE));
                $arrc['merchantid']=$param['merchantid'];
                $SendNotify=new SendNotify();
                $SendNotify->task_biz_notify($arrc);
                $ActionLogs->writelog("osapi", "notify", "event/sendnotify", "发送推送信息:(".$r.")".$notify_url, $arrc);

            }

        }
    }

    public function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {

            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));

                    }
                }

            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/json; charset=utf-8',

            'Content-Length: ' . strlen($param)));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}